﻿using DAL;
using NLog;
using System.Reflection;
using Topshelf;

namespace WebApi2022
{
    public class WindowsService : Topshelf.ServiceControl
    {
        public bool Start(HostControl hostControl)
        {
            Thread thread = new Thread(() =>
            {
                try
                {
                    var builder = WebApplication.CreateBuilder();

                    // Add services to the container.

                    builder.Services.AddControllers();
                    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
                    builder.Services.AddEndpointsApiExplorer();
                    builder.Services.AddSwaggerGen();

                    LiteSqlFactory.GetSession(); //预热
                    Console.WriteLine("预热完成");

                    builder.Services.AddScoped<Dapper.LiteSql.ISession, Dapper.LiteSql.ISession>(serviceProvider =>
                    {
                        return LiteSqlFactory.GetSession();
                    });

                    builder.Services.AddSingleton<Logger, Logger>(serviceProvider =>
                    {
                        return LogManager.GetCurrentClassLogger();
                    });

                    var app = builder.Build();

                    // Configure the HTTP request pipeline.
                    //if (app.Environment.IsDevelopment())
                    {
                        app.UseSwagger();
                        app.UseSwaggerUI();
                    }

                    //app.UseHttpsRedirection();

                    //app.UseAuthorization();

                    string _basePath = Path.GetDirectoryName(Uri.UnescapeDataString(Assembly.GetExecutingAssembly().Location));
                    Console.WriteLine(_basePath);
                    LogManager.LoadConfiguration(_basePath + "/NLog.config");

                    app.MapControllers();

                    app.Run();

                    /*
                    ILiteSqlClient GetClient()
                    {
                        ILiteSqlClient db = new LiteSqlClient(
                                "Data Source=localhost;Port=3306;User ID=root;Password=123456;Initial Catalog=litesql_test;Charset=utf8mb4;SslMode=none;Allow User Variables=True;",
                                DBType.MySQL, new MySQLProvider());

                        return db;
                    }*/
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            });
            thread.IsBackground = true;
            thread.Start();

            return true;
        }

        public bool Stop(HostControl hostControl)
        {
            return true;
        }
    }
}
